package com.geekbang.thinking.in.spring.dependency.injection;

import com.geekbang.thinking.in.spring.dependency.injection.annotation.UserGroup;
import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collection;

/**
 * {@link Qualifier} 注解依赖注入
 *
 */
public class QualifierAnnotationDependencyInjectionDemo {

    @Autowired
    private User user;  // superUser -> primary = true

    @Autowired
    @Qualifier("user")     // 指定 Bean 的名称或 ID
    private User namedUser;

    // 整体上下文中存在 4 个 User 类型的 Bean: superUser、user、user1、user2

    @Autowired
    private Collection<User> users;     // 4 个 Bean

    @Autowired
    @Qualifier
    private Collection<User> qualifiedUsers;    // 2 个 Bean（user1 + user2）

    @Bean
    @Qualifier  // 进行逻辑分组
    public User user1() {
        User user = new User();
        user.setId(7L);
        return user;
    }

    @Bean
    @Qualifier
    public User user2() {
        User user = new User();
        user.setId(8L);
        return user;
    }

    @Bean
    @UserGroup
    public User user3() {
        User user = new User();
        user.setId(9L);
        return user;
    }


    public static void main(String[] args) {
        // 创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration Class (配置类) -> Spring Bean
        applicationContext.register(QualifierAnnotationDependencyInjectionDemo.class);

        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);

        String xmlResourcePath = "classpath:META-INF/dependency-lookup-context.xml";

        beanDefinitionReader.loadBeanDefinitions(xmlResourcePath);

        // 启动应用上下文
        applicationContext.refresh();

        // 依赖查找 AnnotationDependencyFieldInjectionDemo Bean
        QualifierAnnotationDependencyInjectionDemo demo = applicationContext.getBean(QualifierAnnotationDependencyInjectionDemo.class);

        // 期待输出 superUser Bean
        System.out.println("demo.user = " + demo.user);

        // 期待输出 user Bean
        System.out.println("demo.namedUser = " + demo.namedUser);

        // 输出 5 个 （user、superUser、user1、user2、user3）
        System.out.println("demo.users = " + demo.users);

        // 输出 3 个 （user1、user2、user3）
        System.out.println("demo.qualifiedUsers = " + demo.qualifiedUsers);

        // 显示关闭上下文
        applicationContext.close();
    }

}
